package com.itheima.scheduler.elasticjob.springboot.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.JobRootConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.itheima.scheduler.elasticjob.springboot.job.FileBackupJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @Auther: Admin
 * @Date: 2021/7/14 14:07
 * @Description: version 1.0
 */
//@Configuration
public class ElasticJobConfig {

    @Autowired
    private CoordinatorRegistryCenter registryCenter;
    @Autowired
    private FileBackupJob fileBackupJob;

    /**
     * 配置任务详细信息
     *
     * @param jobClass               任务执行类
     * @param cron                   执行策略
     * @param shardingTotalCount     分片数量
     * @param shardingItemParameters 分片个性化参数
     * @return
     */
    private LiteJobConfiguration createJobConfiguration(final Class<? extends SimpleJob>
                                                                jobClass,
                                                        final String cron,
                                                        final int shardingTotalCount,
                                                        final String shardingItemParameters) {
        // 定义作业核心配置，创建builder
        JobCoreConfiguration.Builder simpleCoreConfigBuilder =
                JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount);

        if (!StringUtils.isEmpty(shardingItemParameters)) {
            simpleCoreConfigBuilder.shardingItemParameters(shardingItemParameters);
        }

        JobCoreConfiguration jobCoreConfiguration = simpleCoreConfigBuilder.build();

        // 定义SIMPLE类型配置。通过jobCoreConfiguration创建simpleJobConfiguration
        SimpleJobConfiguration simpleJobConfig = new
                SimpleJobConfiguration(jobCoreConfiguration, jobClass.getCanonicalName());

        // 定义Lite作业根配置
        JobRootConfiguration simpleJobRootConfig =
                LiteJobConfiguration.newBuilder(simpleJobConfig).overwrite(true).build();

        return (LiteJobConfiguration) simpleJobRootConfig;
    }

    /**
     * 任务启动
     *
     * @return
     */
    @Bean(initMethod = "init")
    public SpringJobScheduler initSimpleElasticJob() {
        SimpleJob job1 = fileBackupJob;
        SpringJobScheduler jobScheduler = new SpringJobScheduler(job1,
                registryCenter,
                createJobConfiguration(job1.getClass(), "0/3 * * * * ?", 3, null));
        return jobScheduler;
    }

}
